/**  
 * All rights Reserved, Designed By http://www.pete-cat.com/
 * @Title:  SystemWebMvcRegistrationsAdapter.java   
 * @Package com.petecat.riskmanage.exception.handler   
 * @Description:TODO(用一句话描述该文件做什么)   
 * @author: 成都皮特猫科技     
 * @date:2017年9月5日 上午10:13:38   
 * @version V1.0 
 * @Copyright: 2017 www.pete-cat.com Inc. All rights reserved. 
 * 注意：本内容仅限于成都皮特猫信息技术有限公司内部传阅，禁止外泄以及用于其他的商业目
 */  
package com.petecat.ruleengine.core.config.mvc;

import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.petecat.ruleengine.core.constant.SystemConstant;
import com.petecat.ruleengine.core.exception.CommonException;
import com.petecat.ruleengine.core.exception.handler.ExceptionHandlerResolver;
import com.petecat.ruleengine.core.redis.SystemRedisTemplate;
import com.petecat.ruleengine.core.util.DataCopy;
import com.petecat.ruleengine.protocol.global.dto.DictionaryDTO;
import com.petecat.ruleengine.protocol.sso.vo.SsoUserInfoVO;

import net.hryx.sso.result.util.UserTokenUtils;
import net.hryx.sso.vo.SSOUserTokenInfo;

/**   
 * @ClassName:  SystemWebMvcRegistrationsAdapter   
 * @Description:系统web注册适配
 * @author: admin
 * @date:   2017年9月5日 上午10:13:38   
 */
@Component
public class SystemWebMvcRegistrationsAdapter extends WebMvcConfigurerAdapter  {

	@Autowired
	private SystemRedisTemplate systemRedisTemplate;
	
	
	private Logger logger = LoggerFactory.getLogger(SystemWebMvcRegistrationsAdapter.class);
	
	/**   
	 * <p>Title: configureHandlerExceptionResolvers</p>   
	 * <p>Description: </p>   
	 * @param exceptionResolvers   
	 * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter#configureHandlerExceptionResolvers(java.util.List)   
	 */  
	@Override
	public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
		exceptionResolvers.add(0,new ExceptionHandlerResolver());
		super.configureHandlerExceptionResolvers(exceptionResolvers);
	}

	/**   
	 * <p>Title: addInterceptors</p>   
	 * <p>Description: </p>   
	 * @param registry   
	 * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter#addInterceptors(org.springframework.web.servlet.config.annotation.InterceptorRegistry)   
	 */  
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new HandlerInterceptor() {
			@Override
			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
					throws Exception {
				String authorization = request.getHeader("Authorization");
				List<DictionaryDTO> urls = systemRedisTemplate.hGetListObject(SystemConstant.SYS_DICTIONARY_KEY,SystemConstant.NOT_LOGIN_URL_KEY, DictionaryDTO.class);
				boolean checkLogin = true;
				if(!CollectionUtils.isEmpty(urls)) {
					Optional<DictionaryDTO> dtoOptions =  urls.parallelStream().filter(url->StringUtils.isNotBlank(url.getParmname()) && request.getRequestURI().startsWith(url.getParmname())).findFirst();
					if(dtoOptions.isPresent()) {
						logger.debug("检查到当前的地址{}不需要登录",request.getRequestURI());
						checkLogin = false;
					}
				}
				//需要登录
				if(checkLogin) {
					logger.debug("检查到当前的地址{}需要登录，传入的token为：{}",request.getRequestURI(),authorization);
					if(StringUtils.isBlank(authorization)) {
						throw new CommonException(-10,null,null);
					}
					net.hryx.sso.result.Result<SSOUserTokenInfo> tokenResult = UserTokenUtils.getTokenUserInfo(authorization);
					SsoUserInfoVO infoVO = null;
					if(tokenResult.isSuccess()) {
						infoVO = new SsoUserInfoVO();
						DataCopy.copyData(tokenResult.getValue(), infoVO);
						request.setAttribute("CURRENT_USER_INFO",infoVO);
					}else {
						if( -200006 == tokenResult.getError().getCode()) {
							throw new CommonException(-9,null,null);
						} 
					}
					boolean checkPower = true;
					urls = systemRedisTemplate.hGetListObject(SystemConstant.SYS_DICTIONARY_KEY,SystemConstant.NOT_POWER_URL_KEY, DictionaryDTO.class);
					//不需要授权
					if(!CollectionUtils.isEmpty(urls)) {
						Optional<DictionaryDTO> dtoOptions =  urls.parallelStream().filter(url->StringUtils.isNotBlank(url.getParmname()) && request.getRequestURI().startsWith(url.getParmname())).findFirst();
						if(dtoOptions.isPresent()) {
							logger.debug("检查到当前的地址{}不需要授权",request.getRequestURI());
							checkPower = false;
						}
					}
					//检查权限
					if(checkPower) {
						logger.debug("检查到当前的地址{}需要检查权限",request.getRequestURI());
						List<String> powerUrls = systemRedisTemplate.hGetListObject(SystemConstant.USER_VISTS_AUTH_LIST_KEY, infoVO.getUserId(), String.class);
						Optional<String> dtoOptions =  powerUrls.parallelStream().filter(url->StringUtils.isNotBlank(url) && 
								request.getRequestURI().startsWith(url)).findFirst();
						if(!dtoOptions.isPresent()) {
							throw new CommonException(-4,null,null);
						}
					}
				}
				return true;
			}

			@Override
			public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
					ModelAndView modelAndView) throws Exception {
			}

			@Override
			public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
					Exception ex) throws Exception {
			}
			
		});
		super.addInterceptors(registry);
	}
	
}
